import 'package:flutter/cupertino.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/enums/base_advanced_filter_type.dart';
import 'package:x3_form_core/models/base_advanced_filter_model.dart';

/// author：william on 2021/4/8 09:55
/// email：362661044@qq.com
///
typedef AdvancedFilterChange = Function(BaseAdvancedFilterModel, dynamic);

class BaseAdvancedFilterProvider {
  List<BaseAdvancedFilterModel> models;

  Stream<bool> resetStream;

  final Map<String, dynamic> dataSource;

  final String title;

  /// 设置全部为默认值
  final bool setAllToDefault;

  BaseAdvancedFilterProvider({@required List<BaseAdvancedFilterModel> models, this.title = '高级筛选', this.dataSource = const {}, this.setAllToDefault = true}) {
    this.models = List<BaseAdvancedFilterModel>.from(models.where((element) => element.hidden == false && element.inputType != null).toList());

    /// 勾选全部默认值
    for (BaseAdvancedFilterModel model in models) {
      if (model.inputType == BaseAdvancedFilterType.SingleChoice || model.inputType == BaseAdvancedFilterType.SingleChoiceStyleTwo) {
        if (setAllToDefault) dataSource.addAll({model.fieldName: BaseKeyValueModel(key: -2, value: '全部').toJson()});
      } else if (model.inputType == BaseAdvancedFilterType.MultipleChoice || model.inputType == BaseAdvancedFilterType.MultipleChoiceStyleTwo) {
        if (setAllToDefault)
          dataSource.addAll({
            model.fieldName: [BaseKeyValueModel(key: -2, value: '全部').toJson()]
          });
      } else if (model.inputType == BaseAdvancedFilterType.InputSearchSingleChoice || model.inputType == BaseAdvancedFilterType.InputSearchMultipleChoice) {
        ///模糊搜索类型的默认设置为空
        dataSource.addAll({model.fieldName: []});
      }
      if (model.inputType == BaseAdvancedFilterType.ChoiceDateRange) {
        /// 无需处理
      } else {
        if (setAllToDefault) dataSource.addAll({model.fieldName: -2});
      }
    }
  }

  /// 设置筛选项
  setDataSource(BaseAdvancedFilterModel model, dynamic data) {
    dataSource.addAll({model.fieldName: data});
    emitChange(model);
  }

  /// 获取筛选值
  getDataSource(BaseAdvancedFilterModel model) {
    return this.dataSource[model.fieldName];
  }

  /// 获取值
  getDataKey(BaseAdvancedFilterModel model) {
    var value = getDataSource(model);

    /// 如果是集合
    if (value is List) {
      return value.map((e) {
        if (e is Map) return e['key'];
        if (e is BaseKeyValueModel) return e.key;
        return e;
      }).toList();
    }

    /// 单个的情况
    if (value is Map) return value['key'];

    if (value is BaseKeyValueModel) return value.key;

    /// 如果不知道类型直接返回
    return value;
  }

  /// 获取fieldName 和 对应的值
  getAllDataKeyMap() {
    Map<String, dynamic> params = {};
    for (BaseAdvancedFilterModel model in this.models) {
      params.addAll({model.fieldName: getDataKey(model)});
    }
    return params;
  }

  /// 获取事件改变值监听
  AdvancedFilterChange _changeListener;

  void onChangeListener(AdvancedFilterChange listener) {
    _changeListener = listener;
  }

  /// 发送改变监听
  void emitChange(BaseAdvancedFilterModel model) {
    if (_changeListener != null) {
      _changeListener(model, this.getDataSource(model));
    }
  }

  /// 验证器
  bool validationDataSource({bool isShowToast = true, String head = ""}) {
    String _errorText;
    for (BaseAdvancedFilterModel item in this.models) {
      var currentData = this.dataSource[item.fieldName];
      bool _isEmpty = currentData == null || currentData.toString().trim().isEmpty;

      /// 是否必填
      if (item.required == true) {
        if (_isEmpty) {
          _errorText = '$head${item.name}不能为空！';
          break;
        }
      }
    }
    bool isSave = _errorText != null ? false : true;
    if (isSave == false && isShowToast) BaseUtils.showToast(_errorText);
    return isSave;
  }

  static BaseAdvancedFilterProvider of(BuildContext context, {bool listen = false}) {
    return Provider.of<BaseAdvancedFilterProvider>(context, listen: listen);
  }
}
